package com.project.controller;


import com.project.constant.JwtClaimsConstant;
import com.project.entity.Users;
import com.project.properties.JwtProperties;
import com.project.result.Result;
import com.project.service.UserService;
import com.project.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import static com.project.context.BaseContext.userType;

@RestController
@RequestMapping("/login")
@Slf4j
public class LoginController {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;

    /**
     * 登录
     *
     * @param
     * @return
     */
    @PostMapping
    public Result<Map<String, Object>> login(@RequestParam Integer userId, @RequestParam String password) {

        log.info("员工登录：{} {}", userId, password);
        Long userType = userService.getId(userId);// 获取用户类型

        // 1. 封装登录信息
        Users loginUser = new Users();
        loginUser.setUserId(userId);
        loginUser.setPassword(password);

        // 2. 调用 service 进行身份验证
        Users authenticatedUser = userService.login(loginUser);
        if (authenticatedUser == null) {
            return Result.error("用户名或密码错误");
        }

        // 3. 生成 JWT token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, userId);
        claims.put(JwtClaimsConstant.USER_TYPE, userType);
        String token = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                claims);

        // 4. 构造返回数据（必须包含 token！）

        Map<String, Object> responseData = new HashMap<>();
        responseData.put("token", token);

        responseData.put("userType",userType); // 或从 authenticatedUser 获取

        return Result.success(responseData);
    }

}